package nowcoder.offer;

/**
 * 表示数值的字符串
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-08-29 9:53
 */
public class IsNumeric {

    public boolean solution(char[] str){
        if (str==null || str.length ==0) return false;
        int e = -1,p = -1; //分别记录e与.的位置
        int i = 0;
        for (; i < str.length-1; i++) {
            if (isNumber(str[i])){
                //如果是数字
                continue;
            }else{
                switch (str[i]){
                    case '+':if (i==0 || str[i-1] == 'e' || str[i-1] == 'E')break;
                                else return false;
                    case '-':if (i==0 || str[i-1] == 'e' || str[i-1] == 'E') break;
                             else return false;
                    case '.':if (p != -1 || (e != -1 && e < i)) return false;
                             else p = i;break;
                    case 'e':if (e != -1) return false;
                             else e = i;break;
                    case 'E':if (e != -1) return false;
                            else e = i;break;
                    default:return false;
                }
            }
        }
        if (!isNumber(str[i])) return false;

        return true;
    }

    public boolean isNumber(char c){
        if (c - '0' >=0 && '9' - c >=0)
            return true;
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new IsNumeric().solution("+100".toCharArray()));
        System.out.println(new IsNumeric().solution("5e2".toCharArray()));
        System.out.println(new IsNumeric().solution("-123".toCharArray()));
        System.out.println(new IsNumeric().solution("3.1415".toCharArray()));
        System.out.println(new IsNumeric().solution("-1E-16".toCharArray()));
        System.out.println(new IsNumeric().solution("12e".toCharArray()));
        System.out.println(new IsNumeric().solution("1a3.14".toCharArray()));
        System.out.println(new IsNumeric().solution("+-5".toCharArray()));
        System.out.println(new IsNumeric().solution("12e+4.3".toCharArray()));
    }
}
